<?php
/**
 * User: b179a9
 * Date: 10/8/11
 * Time: 5:14 PM
 */

namespace Managers;

class Payments extends BaseManager
{

    const API_URI = 'https://api-3t.sandbox.paypal.com/nvp';

    const SESSION_NAME = 'payment';

    private $monetPrice = 20;

    /**
     * Выволняет начальный запрос для Express Checkout.
     * @throws \Exception
     * @param $moneyCount
     * @return void
     */
    public function setExpressPayment($moneyCount)
    {
        $adapter = new \Payments_PayPal(self::API_URI);

        $baseUrl = \Zend_Registry::get('config')->resources->frontController->baseUrl;
        $returnUrl = $baseUrl . '/payment/complete';
        $canceledUrl = $baseUrl . '/payment/cancelled';

        $items = array(array('name' => 'Pirates money',
                             'desc' => 'Pirates money. <h1>TreasureAce.ca.</h1>',
                             'price' => $this->monetPrice,
                             'quantity' => $moneyCount));
        $reply = $adapter->ecSetExpressCheckout($returnUrl, $canceledUrl, $items);

        if (!$reply->isSuccessful()) {
            throw new \Exception('Cannot connect you PayPal service. Please, try again later.');
        }

        $replyData = $adapter->parse($reply->getBody());
        if (!preg_match('/success/i', $replyData['ACK'])) {
            throw new \Exception('Response from PayPal is not success.');
        }

        $session = new \Zend_Session_Namespace(self::SESSION_NAME);
        $session->moneyCount = $moneyCount;
        $amount = $this->monetPrice * $moneyCount;
        $session->amount = $amount;

        $token = $replyData['TOKEN'];
        header('Location: ' .
               $adapter->api_expresscheckout_uri .
               '?&cmd=_express-checkout&token=' . $token);
    }

    /**
     * Выполняет платежный запрос ExpressCheckout.
     * @throws \Exception
     * @param $userId
     * @param $params
     * @return void
     */
    public function doExpressPayment($userId, $params)
    {
        $token = $params['token'];
        $payer_id = $params['PayerID'];

        $session = new \Zend_Session_Namespace(self::SESSION_NAME);
        $amount = $session->amount;

        $user = $this->_em->find(Users::TABLE, $userId);
        if (!$user) {
            throw new \Exception('Such user does not exist.');
        }

        $adapter = new \Payments_PayPal(self::API_URI);
        $reply = $adapter->ecDoExpressCheckout($token, $payer_id, $amount);

        if (!$reply->isSuccessful()) {
            throw new \Exception('Cannot connect you PayPal service. Please, try again later.');
        }

        $replyData = $adapter->parse($reply->getBody());

        if (!preg_match('/success/i', $replyData['ACK']) || !preg_match('/completed/i', $replyData['PAYMENTSTATUS'])) {
            throw new \Exception('Payment status is not completed.');
        }

        $moneyCount = $session->moneyCount;
        $user->setMoney($user->getMoney() + $moneyCount);
        $this->_em->persist($user);

        $moneyOrder = new \Catalog\MoneyOrders();
        $moneyOrder->setMoneyCount($moneyCount);
        $moneyOrder->setTransaction($replyData['TRANSACTIONID']);
        $moneyOrder->setUser($user);
        $moneyOrder->setTime(new \DateTime());
        $this->_em->persist($moneyOrder);

        $this->_em->flush();
        $session->amount = 0;
    }

    /**
     * Выполняет прямой платеж.
     * @throws \Exception
     * @param $userId
     * @param $params
     * @return
     */
    public function doDirectPayment($userId, $params) {

        $adapter = new \Payments_PayPal(self::API_URI);
        $moneyCount = intval($params['money']);

        $amount = $moneyCount * $this->monetPrice;

        if($amount == 0) {
            throw new \Exception('No items to buy.');
        }

        $reply = $adapter->doDirectPayment($amount, $params, '127.0.0.1');
        $replyData = $adapter->parse($reply->getBody());

         if (!preg_match('/success/i', $replyData['ACK'])) {
            throw new \Exception('Payment status is not success.');
         }

        $user = $this->_em->find(Users::TABLE, $userId);
        if(!$user) {
            throw new \Exception('Such user does not exist.');
        }

        $user->setMoney($user->getMoney() + $moneyCount);
        $this->_em->persist($user);

        $moneyOrder = new \Catalog\MoneyOrders();
        $moneyOrder->setMoneyCount($moneyCount);
        $moneyOrder->setTransaction($replyData['TRANSACTIONID']);
        $moneyOrder->setUser($user);
        $moneyOrder->setTime(new \DateTime());
        $this->_em->persist($moneyOrder);

        $this->_em->flush();
        return $moneyOrder;

    }

}
